//Alberto De Pena
//Kyle Weaver
//Aldo Campos
//Alex yang
#ifndef NIM_HEADER
#define NIM_HEADER
#include "nim.h";
#endif

#ifndef IOSTREAM
#define IOSTREAM
#include <iostream>
#endif

using namespace std;

void server_main ( int argc, char** argv ) 
{
	char recvBuf[MAX_RECV_BUF+1];
	char sendBuf[MAX_SEND_BUF+1];
	char host[MAX_HOST+1];
	char service[MAX_SERVICE+1];
	char answer[MAX_LINE+1];
	char server_user[MAX_LINE+1];
	char client[MAX_RECV_BUF+1];
	SOCKET       lsock;             // listening socket handle
    SOCKET       csock;             // connected socket handle
	sockaddr_in   csin;             // holds client's socket information 
	int clen = sizeof(csin);      // size of client's sockaddr_in struct

	cout << "What is your name? ";   
	cin.getline(server_user,MAX_LINE);

	strcpy_s(service,MAX_SERVICE, UDPPORT_NIM);
	SOCKET s = passivesock(service,"UDP");

	if (s != INVALID_SOCKET) 
	{
		cout << endl << "Waiting for connection ..." << endl << endl;
		int len = udp_recv(s,recvBuf,MAX_RECV_BUF,host,service);
		while (len > 0) 
		{
			strcpy_s(sendBuf,MAX_SEND_BUF,server_user);
			len = udp_send(s,sendBuf,(int)strlen(sendBuf)+1,host,service);
			len = udp_recv(s,recvBuf,MAX_RECV_BUF,host,service);

			char temprevc [MAX_RECV_BUF];
			int count =0;
			for(int i = 11 ; recvBuf[i] != '\0'; i++)
			{
				temprevc[count] = recvBuf[i];
				count ++;
			}

			temprevc[count]='\0';
			strcpy_s(client,MAX_RECV_BUF, temprevc);

			cout << "Would you like to accept a challenge from " << client << " (yes)? ";
			cin.getline(answer,MAX_LINE);

			if( _stricmp(answer ,"yes") == 0 )
			{
				strcpy_s(sendBuf,MAX_SEND_BUF+1,"Yes\0");
				len = udp_send(s,sendBuf,(int)strlen(sendBuf)+1,host,service);

				int stat = wait(s,5,0);
				while (stat > 0) 
				{
					len = udp_recv(s,recvBuf,MAX_RECV_BUF+1,host,service);
					if( _stricmp( recvBuf, "GREAT!\0") == 0 )
					{
						strcpy_s(service,MAX_SERVICE,TCPPORT_NIM);
						lsock = passivesock(service,"tcp"); 
						csock = accept(lsock,(LPSOCKADDR) &csin, &clen); 
						closesocket(s);

					if (csock == INVALID_SOCKET)
						cout << "Unable to accept connection request" << endl;
					  
					if( lsock != INVALID_SOCKET )
							play_Nim(csock,false,host);

						closesocket(csock);
						len=0;
					}
					stat = wait(lsock,5,0);
				}
				closesocket(lsock);
			}
			else if( _stricmp(answer, "No\0" ) == 0 )
			{
				strcpy_s(sendBuf,MAX_SEND_BUF+1,"No\0");
				len = udp_send(s,sendBuf,(int)strlen(sendBuf)+1,host,service);
			}
		}
	}
}